// routes/paymentRoutes.js - 新建这个文件
const express = require('express');
const router = express.Router();
const db = require('../config/database');

// 支付路由访问日志
router.use((req, res, next) => {
    console.log(`🛣️ 支付路由访问: ${req.method} ${req.originalUrl}`);
    next();
});

// 获取钱包余额
router.get('/balance/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        console.log(`💰 获取钱包余额，用户ID: ${userId}`);

        // 查询钱包余额
        const [wallets] = await db.execute(
            'SELECT balance FROM wallets WHERE user_id = ?',
            [userId]
        );

        const balance = wallets.length > 0 ? wallets[0].balance : 0;

        console.log(`✅ 返回余额数据: ${balance}`);

        res.json({
            success: true,
            data: {
                balance: balance,
                availableBalance: balance,
                frozenBalance: 0
            }
        });

    } catch (error) {
        console.error('❌ 获取余额失败:', error);
        res.status(500).json({
            success: false,
            message: '获取余额失败'
        });
    }
});

// 获取代拿员收入统计
router.get('/courier-users/income/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        console.log(`💰 获取代拿员收入统计，用户ID: ${userId}`);

        // 查询代拿员历史收入（按已完成订单统计）
        const [income] = await db.execute(
            `SELECT
                COALESCE(SUM(o.final_fee), 0) as total,
                COALESCE(SUM(CASE WHEN DATE(o.completed_at) = CURDATE() THEN o.final_fee ELSE 0 END), 0) as today,
                COALESCE(SUM(CASE WHEN YEAR(o.completed_at) = YEAR(CURDATE()) AND MONTH(o.completed_at) = MONTH(CURDATE()) THEN o.final_fee ELSE 0 END), 0) as month
             FROM orders o
             JOIN courier_users cu ON o.courier_user_id = cu.id
             WHERE cu.user_id = ? AND o.status = 5`,
            [userId]
        );

        const incomeData = income.length > 0 ? income[0] : {
            total: 0,
            today: 0,
            month: 0
        };

        // 查询钱包余额，作为当前可提现金额
        const [wallets] = await db.execute(
            'SELECT balance FROM wallets WHERE user_id = ?',
            [userId]
        );
        const available = wallets.length > 0 ? Number(wallets[0].balance || 0) : 0;

        res.json({
            success: true,
            data: {
                total: Number(incomeData.total || 0),
                today: Number(incomeData.today || 0),
                month: Number(incomeData.month || 0),
                available
            }
        });

    } catch (error) {
        console.error('❌ 获取收入失败:', error);
        res.status(500).json({
            success: false,
            message: '获取收入失败'
        });
    }
});

module.exports = router;